//*************************************************************************//
//*           _____   ____________            ______               __     *//
//*          / /__ \ / ____/ ____/           / ____/___  _________/ /     *//
//*     __  / /__/ // __/ / __/    ______   / /_  / __ \/ ___/ __  /      *//
//*    / /_/ // __// /___/ /___   /_____/  / __/ / /_/ / /  / /_/ /       *//
//*    \____//____/_____/_____/           /_/    \____/_/   \__,_/        *//
//*                                                                       *//
//*     Copyright (c) 2006 Ford Argentina. All Rights Reserved.           *//
//*                                                                       *//
//*************************************************************************//

package ar.com.ford.it.webengine.facade;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;

public class FacadeProvider {
	private static final String CLASS_NAME = FacadeProvider.class.getName();
	private static final ILogger log = LogFactory.getInstance().getLogger(CLASS_NAME);
	
	private static String FACADE_ID = "asdjefwfn8764wdv23cn354we";
	
	
	public static Object getFacade(HttpServletRequest request, Class claze) {
		String METHOD_NAME = "getFacade";
		log.entering(CLASS_NAME, METHOD_NAME);
		
		Object result = null;
		
		try {
			HttpSession httpSession = request.getSession();
			result = httpSession.getAttribute(FACADE_ID);
			
			if (result == null) {
				result = createFacade(claze);
				httpSession.setAttribute(FACADE_ID, result);
			}
			else {
				if (!result.getClass().getName().equals(claze)) {
					result = createFacade(claze);
					httpSession.setAttribute(FACADE_ID, result);
				}
			}
			
		}
		catch (Exception e) {
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME, "Error al tratar de obtener el facade", e);
		}
		
		log.exiting(CLASS_NAME, METHOD_NAME);
		return result;
	}
	
	private static Object createFacade(Class claze) throws Exception {
		return claze.newInstance();
	}
}
